<template>
    <div class="inners_box">
      <el-form inline size="small" style="background: #174F7F;padding:20px 0 10px 20px;border-radius: 10px;">
        <el-form-item>
          <label slot="label" style="color: #fff;">起始日期</label>
          <el-date-picker
            v-model="time"
            type="daterange"
            :clearable="false"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="loadList(true)"
            >搜索</el-button
          >
          <el-button type="primary" icon="el-icon-setting" @click="reset()"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
  
          <div class="pon box-card-btm">
            <div class="pom">
              <div class="pom-link">
                <div class="total"> {{ total1.t1 }} </div>
                <h3 class="chart-card-title">供应商注册数量<label class="btns" @click="open(0)">查看</label></h3>
              </div>
              <div class="pom-link">
                <div class="total"> {{ total1.t2 }}
                </div>
                <h3 class="chart-card-title">注册通过数量 <label class="btns" @click="open(1)">查看</label></h3>
                
              </div>
              <div class="pom-link">
                  <div class="total">{{ total1.t3 }}
                  </div>
                  <h3 class="chart-card-title">注册驳回数量 <label class="btns" @click="open(2)">查看 </label></h3>
                 
              </div>
            </div>
          </div>
          <div class="pon box-card-btm">
            <div class="pom">
              <div class="pom-link">
                <div class="total"> {{ total2.t1 }}
                 </div>
                <h3 class="chart-card-title">供应商申请入库次数
                  <label class="btns" @click="open(3)">查看
                  </label>
                </h3>
              </div>
              <div class="pom-link">
                <div class="total"> {{ total2.t2 }}
                  </div>
                <h3 class="chart-card-title">入库申请通过次数
                  <label class="btns" @click="open(4)">查看
                  </label>
                </h3>
              </div>
              <div class="pom-link">
                 <div class="total">{{ total2.t3 }}
                  </div>
                <h3 class="chart-card-title">入库申请驳回次数
                   <label class="btns" @click="open(5)">查看
                  </label>
                </h3>
              </div>
            </div>
          </div>

          <div class="pon box-card-btm">
            <!-- <div class="pon-title">考核评分统计</div> -->
            <div class="pom">
              <div class="pom-link">
                 <div class="total"> {{ total3.t1 }} 
                </div>
                <h3 class="chart-card-title">暂停3个月的供应商数量
                  <label class="btns" @click="open(6)">查看
                  </label>
                </h3>
              </div>
              <div class="pom-link">
                 <div class="total"> {{ total3.t2 }}
                  </div>
                <h3 class="chart-card-title">暂停1年的供应商数量
                   <label class="btns" @click="open(7)">查看
                  </label>
                </h3>
              </div>
              <div class="pom-link">
                 <div class="total">{{ total3.t3 }}
                  </div>
                <h3 class="chart-card-title">黑名单中的供应商数量
                   <label class="btns" @click="open(8)">查看
                  </label>
                </h3>
              </div>
            </div>
          </div>
      <!-- <i class="el-icon-coin icon-bar"></i> -->

      <div class="box-card-btm">
        <el-row :gutter="10">
          <el-col :span="17">
             <!-- <div class="pon-title">供应商入库类别统计</div> -->
              <div id="bar-chart" style="height: 383px;background: #174F7F;border-radius: 10px;"></div>
          </el-col>
          <el-col :span="7">
            <div class="ohter-box">
              <div class="pom-len">
                <div class="total"> {{ total4.t1 }} </div>
                  <h3 class="chart-card-title">所有通知公告统计
                    <label class="btns" @click="open(9)">查看
                  </label>
                  </h3>
              </div>
              <div class="pom-len">
                 <div class="total"> {{ total4.t2 }}</div>
                <h3 class="chart-card-title">通知公告分类统计
                   <label class="btns" @click="open(10)">查看
                  </label>
                </h3>
              </div>
            </div>
          </el-col>
        </el-row>
       
      </div>

      <Bar ref="createBar"></Bar>
      <List ref="createList"></List>
      <SupplierList ref="createSupplierList"></SupplierList>

       <el-dialog
      title="分类通知公告统计"
      :visible.sync="dialogClassifyVisible"
      width="50%"
      custom-class="scrollable-dialog"
      :close-on-click-modal="false"
    >
      <el-row :gutter="20">
          <el-col :span="8" v-for="(item,index) in classifyData" :key="index">
            <el-card class="box-card">
              <h3 class="chart-card-title" style="color:#333">{{item.name}}</h3>
              <div class="total">
                <i class="el-icon-coin icon-bar"></i>{{ item.count }}
              </div>
            </el-card>
          </el-col>
        </el-row>
    </el-dialog>


    <el-dialog
      :title="tips.title"
      :visible.sync="tips.visible"
      width="25%">
      <div style="display: flex;align-items: center;grid-column-gap: 15px;font-size: 16px;justify-content: center;">
        <label>供应商入库总数量（{{ tips.child }}）</label>
        <label>子级分类总数量（{{ tips.children }}）</label>
      </div>
      
      <span slot="footer" class="dialog-footer">
         <el-button type="primary" size="small" @click="tipsClick(1)">查看供应商明细</el-button>
        <el-button type="primary" size="small" @click="tipsClick(2)">查看分类明细</el-button>
      </span>
    </el-dialog>


    </div>
</template>
<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import echarts from "echarts";
import SupplierList from "./supplierList.vue";
import Bar from "./bar.vue";
import List from "./list.vue";
import * as CommonApi from "@/api/supplier_api";
import { getDetailByKey } from "@/api/about_api";
export default {
  components: {
    SupplierList,
    Bar,
    List
  },
  computed: {
    ...mapGetters(["findType"])
  },
  data() {
  const year = new Date().getFullYear();
    return {
      time: [
        moment().startOf('year').format('YYYY-MM-DD'),  // 当年1月1日
        moment().endOf('year').format('YYYY-MM-DD')     // 当年12月31日
      ],
      total1: {
        t1: 0,
        t2: 0,
        t3: 0
      },
      total2: {
        t1: 0,
        t2: 0,
        t3: 0
      },
      total3: {
        t1: 0,
        t2: 0,
        t3: 0
      },
      total4: {
        t1: 0,
        t2: 0
      },
      noticeList: [],
      classifyList: [],
      classifyData: [],
      supplierList: [], //供应商列表
      tips: {
        visible: false,
        title: '',
        child: 0,
        children:0,
        row:{}
      },
      dialogClassifyVisible: false
    };
  },
  mounted() {
    this.loadReg();
    this.loadStore();
    this.initSupplier();
    this.loadPause();
    this.loadBlack();
    this.loadNotice();
  },
  methods: {
    loadList() {
      this.loadReg();
      this.loadStore();
      this.initSupplier();
      this.loadPause();
      this.loadBlack();
      this.loadNotice();
    },
    reset() {
      this.time = [];
      this.loadReg();
      this.loadStore();
      this.initSupplier();
      this.loadPause();
      this.loadBlack();
      this.loadNotice();
    },
    //注册
    async loadReg() {
      let [first = 0, second = 0, last = 0] = await Promise.all([
        this.regList(''),
        this.regList(1),
        this.regList(2)
      ]);
      this.total1.t1 = first
    },
    regList(statusFlag) {
      let param = {};
      param.pageNum = 1;
      param.pageSize = 1000;
      if (this.time && this.time.length) {
        param.registerStartTime = this.time[0];
        param.registerEndTime = this.time[1];
      }
      param.statusFlag = statusFlag;
      param.queryType = this.findType["reg"];
      return new Promise((resolve, reject) => {
        CommonApi.supplierPageFind(param)
          .then(async res => {
            const { code, data } = res;
            if (statusFlag == 1) {
              this.total1.t2 = data.total;
            } else if (statusFlag == 2) {
              this.total1.t3 = data.total;
            } 
            resolve(data.total);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //入库列表
    async loadStore() {
      let [first = 0, second = 0] = await Promise.all([
        this.storeList(1),
        this.storeList(2),
        this.storeList('')
      ]);
   //   this.total2.t1 = parseInt(first) + parseInt(second);
    },
    storeList(storeStatus) {
      let param = {};
      param.pageNum = 1;
      param.pageSize = 1000;
      if (this.time && this.time.length) {
        param.storeStartTime = this.time[0];
        param.storeEndTime = this.time[1];
      }
      param.storeStatus = storeStatus;
      param.storeType = "1";
      return new Promise((resolve, reject) => {
        CommonApi.getSupplierStorePage(param)
          .then(async res => {
            const { code, data } = res;
            if (storeStatus == 1) {
              this.total2.t2 = data.total;
            } else if (storeStatus == 2) {
            //  const result = data.list.filter(v=> !v.newUpdateId && !v.newUpdateStatus)
              //  this.total2.t3 = result.length;
            this.total2.t3 = data.total;
            } else if (storeStatus == '') {
              this.total2.t1 = data.total;
            }
            resolve(data.total);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    //暂停 3月-1年
    async loadPause() {
      let param = {};
      if (this.time && this.time.length) {
        param.pauseStartTime = this.time[0];
        param.pauseEndTime = this.time[1];
      }
      param.pageNum = 1;
      param.pageSize = 1000;
      param.isPaused = 1;
      const { code, data } = await CommonApi.getSupplierStorePage(param);
      this.total3.t1 = 0
      this.total3.t2 = 0
      data.list.forEach(v => {
        const result = this.isWithinMonths(v.pauseTime, v.pauseEndDate);
        if (result) {
          this.total3.t1 += 1;
        } else {
          this.total3.t2 += 1;
        }
      });
    },
    isWithinMonths(startDate, endDate) {
      const start = moment(startDate);
      const end = moment(endDate);
      // 计算月份差
      const monthDiff = end.diff(start, "months", true); // true表示返回浮点数
      return monthDiff <= 3 ? true : false;
    },
    //黑名单
    async loadBlack() {
      let param = {};
      if (this.time && this.time.length) {
        param.addBlacklistStartTime = this.time[0];
        param.addBlacklistEndTime = this.time[1];
      }
      param.pageNum = 1;
      param.pageSize = 1000;
      param.tag = "3";
      const { code, data } = await CommonApi.supplierPageFind(param);
      this.total3.t3 = data.total ?? 0;
    },
    //通知
    async loadNotice() {
      let param = {};
      if (this.time && this.time.length) {
        param.publishStartTime = this.time[0] + " 00:00:00";
        param.publishEndTime = this.time[1] + " 23:59:59";
      }
      param.pageNum = 1;
      param.pageSize = 2000;
      const { code, data } = await CommonApi.getNoticePage(param);
      this.total4.t1 = data.total ?? 0;
      this.noticeList = data.list ?? [];
      this.loadClassify();
    },
    async loadClassify() {
      this.total4.t2 = 0;
      this.classifyList = [];
      const { code, data } = await getDetailByKey("tzfl");
      if (code === 200) {
        if (data) {
          if (data.value) {
            let arr = JSON.parse(data.value);
            let result = []
            arr.forEach(v => {
              if (this.time && this.time.length) { //判断时间是否在返回内
                let strat = this.time[0] + " 00:00:00"
                let end = this.time[1] + " 23:59:59"
                const starttime = new Date(strat);
                const endtime = new Date(end);
                const itemDate = new Date(v.createTime); 
                  // 设置时间为同一天的开始和结束，确保包含整天
                starttime.setHours(0, 0, 0, 0);
                endtime.setHours(23, 59, 59, 999);
                itemDate.setHours(12, 0, 0, 0); // 避免时间比较问题
                if (itemDate >= starttime && itemDate <= endtime) {
                  result.push(v)
                }
              }
            })
            this.classifyList =result
            const sourceNames = this.noticeList.map(v => v.noticeType)
            let total = 0
            this.classifyList.forEach(v => {
              if (sourceNames.includes(v.name)) {
                total += 1
              }
            })
            this.total4.t2 = total
          }
        }
      }
    },
    //==================================供应商类别统计==========================
    async initSupplier() {
      this.supplierList = []
       let [first = [], second = [],filsd = []] = await Promise.all([
        this.getPassSupplier(),
        this.getPausedSupplier(),
        this.getBlacklistSupplier()
       ]);
      this.supplierList = [...first, ...second, ...filsd]
      this.initpint()
    },
    async getPassSupplier() {
       let param = {};
        if (this.time && this.time.length) {
          param.storeStartTime = this.time[0];
          param.storeEndTime = this.time[1];
        }
        param.pageNum = 1
        param.pageSize = 2000;
      param.tag = "1" // 供应商标签 1、合格供应商 2、暂停使用 3、黑名单
          param.storeStatus = "1" //入库状态 0.待审核 1.审核通过 2.审核拒绝
      param.isPaused = 0 // 是否暂停 1.已暂停 0.未暂停
         param.storeType = "1" // 入库类型 1、入库申请 2、更新资料
      return new Promise(async (resolve, reject) => { 
        const { code, data } = await CommonApi.countSupplierStoreBar(param);
        const result = data?.list ?? []
         result.forEach(v => {
          v.applyCategoryId = Number(v.applyCategoryId)
        })
        resolve(result)
      })
    },
    async getPausedSupplier() {
      let param = {};
      if (this.time && this.time.length) {
        param.pauseStartTime = this.time[0];
        param.pauseEndTime = this.time[1];
      }
      param.pageNum = 1
      param.pageSize = 2000;
      param.isPaused =1
      return new Promise(async (resolve, reject) => { 
        const { code, data } = await CommonApi.countSupplierStoreBar(param);
        const result = data?.list ?? []
        result.forEach(v => {
          v.tag = "2"
          v.applyCategoryId = Number(v.applyCategoryId)
        })
        resolve(result)
      })
    },
    async getBlacklistSupplier() {
      let param = {};
      if (this.time && this.time.length) {
        param.addBlacklistStartTime = this.time[0];
        param.addBlacklistEndTime = this.time[1];
      }
      param.pageNum = 1
      param.pageSize = 2000;
      param.tag = "3"
      return new Promise(async (resolve, reject) => { 
        const { code, data } = await CommonApi.supplierPageFind(param);
        const result = data?.list ?? []
         result.forEach(v => {
           v.tag = "3"
          v.applyCategoryId = Number(v.applyCategoryId)
        })
        resolve(result)
      })
    },
    //==================================供应商和分类匹配
     extractIdsFromTree(tree, ids = []) {
        // 遍历当前层级的节点
        tree.forEach(node => {
          // 添加当前节点的ID
          ids.push(node.id);
          
          // 如果有子节点且未超过三级，递归处理
          if (node.children && node.children.length > 0) {
            this.extractIdsFromTree(node.children, ids);
          }
        });
        return ids;
    },
    async initpint() {
       const {data} = await CommonApi.getSupplierCategoryTree()
      const result = data ?? []
      result.forEach(v => {
        v.count = 0
        v.child = []
        if (v.children && v.children.length > 0) {// 有子级
         const categoryIds = this.extractIdsFromTree(v.children)
        //  const categoryIds = v.children.map(n => n.id)
          const str = this.supplierList.filter(m => categoryIds.includes(m.applyCategoryId))
          if(str && str.length > 0) {
            v.count = str.length
            v.child = str
          }
        } else {//没有子级
          this.supplierList.forEach(n => {
            if (Number(n.applyCategoryId) == v.id) {
              v.count += 1
              v.child.push(n)
            }
          })
      
        }
      })
      this.initChart(result)
    },
    //===================================图像渲染
    async initChart(result) {
      const chartDom = document.getElementById("bar-chart");
      const myChart = echarts.init(chartDom);

      let seriesResult = []
      result.forEach((v,i) => {
        let param = {}
        if (v.children && v.children.length == 0) {
          param.value = v.count
          param.name = v.categoryName
          param.child = v.child
          param.children = []
          seriesResult.push(param)
        } else {
          param.value = v.count
          param.name = v.categoryName
          param.children = v.children
          param.child = v.child
          seriesResult.push(param)
        }
      })

    //  const colors = ['#64a1fa', '#b5aff4', '#97e98e', '#f9d870']
      const colors = ['#546fc6', '#92cc77', '#fac859', '#ee6666', '#73c0de', '#8a3de1', '#c8f10f',
							'#f845f1'
						]

      const option = {
        backgroundColor: '#174F7F', // 背景颜色 174F7F
        tooltip: {
          trigger: "axis"
        },
        title: {
          text: "供应商入库类别统计",
          textStyle: {
            color: "#fff",
            fontSize: 18, // 设置标题文字大小
          },
          left: "center",
          top: "5%",
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: '5%',
          top: "25%",
          containLabel: true
        },
        legend: {},
        xAxis: {
          type: "category",
          data: result.map(v=>v.categoryName),
          axisLabel: {
            triggerEvent: true,  // 开启点击事件
            color: "#fff",
            fontSize: 16, // 设置 x 轴文字大小
          },
          axisLine:{lineStyle:{color: '#29b9d7',width:0,type: 'solid'}}
        },
        yAxis: {
          type: "value",
          name: "单位：入库数量",
          nameTextStyle: {
            color: '#fff'
          },
          axisLabel: {
            color: "#fff",
            fontSize: 18, // 设置 x 轴文字大小
          },
          axisLine:{lineStyle:{color: '#57617B',width:0,type: 'solid'}},
           splitLine: {
	                show: true,
	                lineStyle:{color: '#57617B'}
	            }
        },
        series: [
          {
            data: seriesResult,
            type: "bar",
            barWidth: 40,
            itemStyle: {
              //color: "#409eff",
              color: function (param) {
                return colors[param.dataIndex]
              },
              barBorderRadius: [15, 15, 0, 0]
            },
            label: {
              show: true,
              position: "top",
              fontSize: 22,
              color: function (param) {
                return colors[param.dataIndex]
              },
           //   color: "#000",
           // triggerEvent: true
            }
          }
        ]
      };
      myChart.setOption(option);

      myChart.on("click", (params) => {
        this.tips = {
          visible: true,
          title: params.data.name,
          child: params.data.child.length,
          children:params.data.children.length,
          row:params.data
        }
      });
    },
    // ===============================================
    tipsClick(type) {
      if (type == 1) {
        this.$refs.createSupplierList.open(this.tips.row);
      } else {
        if (this.tips.row.children && this.tips.row.children.length === 0) {
          return this.$message.error("该类别下没有子级")
        }
        this.$refs.createBar.open(this.tips.row);
      }
    },
    open(type) {
      if (type == 1) {
        this.$refs.createList.openTable("注册通过列表", 1, "reg");
      } else if (type == 2) {
        this.$refs.createList.openTable("注册驳回列表", 2, "reg");
      } else if (type == 3) {
        this.$refs.createList.openTable("供应商申请入库列表", "", "store");
      } else if (type == 4) {
        this.$refs.createList.openTable("入库申请通过列表", 1, "store");
      } else if (type == 5) {
        this.$refs.createList.openTable("入库申请驳回列表", 2, "store");
      } else if (type == 6) {
        this.$refs.createList.openTable("暂停3个月的供应商列表", 2, "pause");
      } else if (type == 7) {
        this.$refs.createList.openTable("暂停1年的供应商列表", 1, "pause");
      } else if (type == 8) {
        this.$refs.createList.openTable("黑名单供应商列表", 3, "black");
      } else if (type == 9) {
        this.$refs.createList.openTable("通知公告列表", 0, "notice");
      } else if (type == 10) {
        this.classifyTree();
      } else if (type === 0) {
         this.$refs.createList.openTable("注册列表", '', "reg");
      }
    },
    classifyTree() {
      const counts = {}
      const sourceNames = this.classifyList.map(item => item.name)
      // 遍历目标数组
      this.noticeList.forEach(item => {
        // 检查当前项的名称是否在源数组中
        if (sourceNames.includes(item.noticeType)) {
          // 如果存在则统计
          counts[item.noticeType] = (counts[item.noticeType] || 0) + 1
        } 
      })

       let result = []
      sourceNames.forEach(item => {
        let results = counts[item]
         let param = {}
        if (results) {
          param.name = item
          param.count = results
        } else {
          param.name = item
          param.count = 0
        }
        result.push(param)
      })

      this.classifyData = result
      this.dialogClassifyVisible = true
    }
  }
};
</script>
<style scoped>
.pon{
  overflow: hidden;
}
.pon-title{
  margin-bottom: 15px;
  margin-top: 30px;
}
.pom{
  display: flex;
  align-items: center;
  /* background: #072f5f; #174F7F*/
  background: #174F7F;
  padding: 40px 0;
  border-radius: 10px;
}
.pom-link{
  flex: 1;
  color: #333;
  display: flex;
  position: relative;
  align-items: center;
  flex-direction: column;
}
.pom-link + .pom-link {
  border-left: 1px solid #fff;
}
.mpts{
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 290px;
  position: relative;
}
.pom-links{
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.inners_box{
  overflow: hidden;
}


.ohter-box{
  background: #174F7F;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
    justify-content: center;
  height: 383px;
}

.pom-len{
  display: flex;
  align-items: center;
  flex: 1;
    width: 100%;
     justify-content: center;
  flex-direction: column;
}
.pom-len + .pom-len{
  border-top: 1px solid #fff;
}

.chart-card-title {
  color: #fff;
  font-size: 16px;
  line-height: 22px;
  margin: 0;
  position: relative;
}
.total {
  text-overflow: ellipsis;
  word-break: break-all;
  margin-bottom: 0px;
  font-size: 40px;
  overflow: hidden;
  white-space: nowrap;
  font-weight: bold;
  background: linear-gradient(to bottom, #e1cf92, #c3a84a);
  /* 将背景裁剪到文本区域 */
  -webkit-background-clip: text;
  background-clip: text;
  /* 将文本填充颜色设置为透明，以便显示背景渐变 */
  -webkit-text-fill-color: transparent;
}

.mot{
  position: relative;
}
.cms{
  position: absolute;
      bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.btns-link{
  flex: 1;
    padding: 10px;
    color: #fff;
    text-align: center;
    font-weight: bold;
    cursor: pointer;
}
.btns-link:hover{
  color:#fff;
  opacity: 0.7;
}
.c1{
  color:#4b7efb
}
.c2{
  color:#65e23c
}
.c3{
  color:#e57471
}
.c4{
 color:#f2bf88;
}
.c5{
  color:#c4a0f7;
}
.c11{
  background:#4b7efb
}
.c22{
  background:#65e23c
}
.c33{
  background:#e57471
}
.c44{
  background:#f2bf88
}
.c55{
  background:#c4a0f7
}

.btns {
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
    color: #409EFF;
    position: absolute;
    top: 0;
    right: -45px;
}
.btns:hover{
  color:#000;
  opacity: 0.7;
}

.icon-bar {
  margin-right: 10px;
  font-size: 28px;
}
.box-card-btm{
  margin-top: 10px;
}
</style>
<style>
canvas{
  border-radius: 10px;
}
</style>